package com.dataex.app;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.dataex.dbtool.BaseDbcpDao;
import com.dataex.dbtool.DateUtil;
import com.dataex.dbtool.ImpCollUtil;
import com.dataex.dbtool.ImpStringUtil;
import com.dataex.dbtool.PinyinUtils;

@ComponentScan
@Component
public class dataService {

	private final static Logger logger = LoggerFactory.getLogger(dataService.class);

	boolean bStart = false;
	boolean bStartImport = false;

	public dataService() {
		logger.info("tttttt");
	}
	
	@Scheduled(cron = "0 0 0 * * ?")
	public void doAll(){
		doGet();
		doImport();
	}
	
	
	//@Scheduled(cron = "0 0/15 * * * ?")
	public void doGet() {
		
		if (bStart ){
			logger.info("already started, return");
			return;
		}

		bStart = true;
		BaseDbcpDao src = new BaseDbcpDao("222.128.93.123:1433:zxyg:UFDATA_004_2016:sa:`123#@!~ZXYGzxyg", false, 1);
		BaseDbcpDao dst = new BaseDbcpDao("222.128.93.123:1433:zxyg:data:sa:`123#@!~ZXYGzxyg", false, 1);
//		BaseDbcpDao src = new BaseDbcpDao("localhost:1433:MSSQLSERVER:UFDATA_004_2016:sa:1", false, 1);
//		BaseDbcpDao dst = new BaseDbcpDao("localhost:1433:MSSQLSERVER:data:sa:1", false, 1);
		logger.info("-----------------------------------------start --------------------------------------------");
		
		this.doEx_mchk(src, dst); //客户档案
		this.doEx_mchk_gys(src, dst); //供应商档案
		this.doEx_spkfk(src, dst); //存货
		this.doEx_ckjxdj(src, dst); // 销售发货单
		this.doEx_ckjxdj_cgth(src, dst); //采购退货单
		this.doEx_rkjxdj(src, dst); //采购到货单
		this.doEx_rkjxdj_xsth(src, dst); //销售退货单
		bStart = false;
		
		logger.info("-----------------------------------------end --------------------------------------------");
	}
	
	//@Scheduled(cron = "0 0 0 * * ?")
	//@Scheduled(cron = "0 0/15 * * * ?")
	public void doImport() {
		
		if (bStartImport ){
			logger.info("already started, return");
			return;
		}

		bStart = true;
		BaseDbcpDao src = new BaseDbcpDao("222.128.93.123:1433:zxyg:UFDATA_004_2016:sa:`123#@!~ZXYGzxyg", false, 1);
		BaseDbcpDao dst = new BaseDbcpDao("222.128.93.123:1433:zxyg:data:sa:`123#@!~ZXYGzxyg", false, 1);
//		BaseDbcpDao src = new BaseDbcpDao("localhost:1433:MSSQLSERVER:UFDATA_004_2016:sa:1", false, 1);
//		BaseDbcpDao dst = new BaseDbcpDao("localhost:1433:MSSQLSERVER:data:sa:1", false, 1);
		logger.info("-----------------------------------------start --------------------------------------------");
		
		this.doEx_Imp_ckd(src, dst);
		this.doEx_Imp_xsch_fhjl(src, dst);
		this.doEx_Imp_xsth_rkzlys(src, dst);
		this.doEx_Imp_ysjl(src, dst);
		this.doEx_Imp_yp_rkzlys(src, dst);
		this.doEx_Imp_cgth_zlfh(src, dst);
		this.doEx_Imp_cgth_yhjl(src, dst);
		
		bStartImport = false;
		
		logger.info("-----------------------------------------end --------------------------------------------");
	}
	
	public void doGet_local() {
		
		if (bStart ){
			logger.info("already started, return");
			return;
		}

		bStart = true;
//		BaseDbcpDao src = new BaseDbcpDao("222.128.93.123:1433:zxyg:UFDATA_004_2016:sa:`123#@!~ZXYGzxyg", false, 1);
//		BaseDbcpDao dst = new BaseDbcpDao("222.128.93.123:1433:zxyg:data:sa:`123#@!~ZXYGzxyg", false, 1);
		BaseDbcpDao src = new BaseDbcpDao("localhost:1433:MSSQLSERVER:UFDATA_004_2016:sa:1", false, 1);
		BaseDbcpDao dst = new BaseDbcpDao("localhost:1433:MSSQLSERVER:data:sa:1", false, 1);
		logger.info("-----------------------------------------start --------------------------------------------");
		
		this.doEx_mchk(src, dst); //客户档案
		this.doEx_mchk_gys(src, dst); //供应商档案
		this.doEx_spkfk(src, dst); //存货
		this.doEx_ckjxdj(src, dst); // 销售发货单
		this.doEx_ckjxdj_cgth(src, dst); //采购退货单
		this.doEx_rkjxdj(src, dst); //采购到货单
		this.doEx_rkjxdj_xsth(src, dst); //销售退货单
		bStart = false;
		
		logger.info("-----------------------------------------end --------------------------------------------");
	}

	/**
	 * jzt_ckjxdj（出库进销单据表，包含出库、购退单据，具体以表中ddlx字段来区分） 销售发货单, 采购退货单
	 */
	public void doEx_ckjxdj(BaseDbcpDao src, BaseDbcpDao dst) {
		
		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(convert(bigint,convert(timestamp ,convert(money,ufts))))) as newts from Sales_FHD_T where  bReturnFlag =0"; 
		String sql_getData =" use UFDATA_004_2016 select top 5000 "+
				"1 as djbh		"+ //后面会覆盖掉  A21XSD00000001
				",'A21XSD' + cdlcode as u8djbm "+
				",'A21' + T.ccuscode as dwbh "+
				",T.ddate as rq "+
				",T.dcreatesystime as ontime "+
				", case when T.cpersonname is null then 'undefine' else   T.cpersonname end as ywy "+
				",T.cmaker as username	"+
				",'N' as sf_tbj	 "+
				",null as djbh_y	"+
				",'3' as thfs "+
				",'0' as scf	"+
				",null as Dwid_ej"+
				",null as djbh_bd	"+
				",'N' as Sf_ffzp	"+
				",'1' as zpfffs	"+
				",null as tyfk	"+
				",T.cmemo as khbz "+
				",'1' as ddlx "+
				",'6' as danjlx	 "+
				",null as xslx	"+
				",null as pslx	"+
				",'0' as fkfs "+
				",null as cgy 	"+
				",'DWID0001483' as yez "+
				",null as yspd "+
				",null as yuany "+
				",2 as yew_type "+
				",T.dmoddate  as dmrq 	"+
				",'N' as ZT	"+
				",'N' as sf_gxht 	"+
				",(select top 1 cPersonPhone from Person where cPersonCode = cpersoncode) as xsywydh "+
				",W.irowno as Dj_sort "+
				",'A21' + W.cinvcode as spid 	"+
				",W.iquantity as shl "+
				", case when W.itaxunitprice is null then '99' else   W.itaxunitprice end as dj "+//TODO
				", case when W.isum is null then '99' else   W.isum end as hsje "+//TODO
				",W.isettleprice as hesdj	"+
				",W.cbatch as ph "+
				",null as Sf_cxsp "+
				",null as cxms "+
				",W.fsalecost as lshj "+
				",W.isettlenum as jsje "+
				",W.iinvsprice as dckhcbj "+
			"from Sales_FHD_T as T inner join Sales_FHD_W as W on T.dlid = W.dlid "+
			"where convert(bigint,convert(timestamp ,convert(money,ufts))) > %d and convert(bigint,convert(timestamp ,convert(money,ufts))) <=%d "+
			"order by T.dlid asc, irowno asc ";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 1);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = " if NOT EXISTS( select top 1 1 from jzt_ckjxdj where left(djbh,6)='A21XSD' and LEN(djbh)=14 )"+
		"select djbh = 'A21XSD00000001'"+
		"else "+
		" select djbh = 'A21XSD' + right('00000000' + cast( cast(right(max(djbh),8) as int) + 1 as nvarchar(8)),8) from jzt_ckjxdj where left(djbh,6)='A21XSD' and LEN(djbh)=14";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("djbh");
		int startIndex = Integer.parseInt(code.substring(6));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){
			
			this.parseData(1, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_ckjxdj", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_ckjxdj", updateMapData, 
						ImpStringUtil.commaStringToSetStr("u8djbm", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 1, newTime);
		}
		
		logger.info("finish, datasize:{},updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}

	/**
	 * jzt_rkjxdj（入库进销单据，包含入库、销退，具体以表中rktype字段来区分)
	 * 
	 * 销售退货单, 采购到货单
	 */
	public void doEx_rkjxdj(BaseDbcpDao src, BaseDbcpDao dst) {
		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(ufts)) as newts from PU_ArrivalVouch  ";
		String sql_getData =" use UFDATA_004_2016 select top 5000 "+
				"1 as djbh "+ //后面会覆盖掉  A21CGD00000001
				",'A21CGD' + cCode as u8djbm "+
				",'A21' + cVenCode as dwbh" + //后面会覆盖掉
				",T.ddate as rq "+
				",T.cMakeTime as ontime "+
				",1 as rktype "+
				", 0 as scf "+
				", null as lxr "+
				", null as shouhy "+
				", 'undefined' as username "+
				", case when T.cReviser is null then 'undefine' else   T.cReviser end as ywy "+
				", null as lxrdh "+
				", null as thlb "+
				", 'DWID0001483' as yez "+
				",  W.ivouchrowno as dj_sort " +
				", 'A21'+cInvCode as spid " + //后面会覆盖掉  A21CGD00000001
				", W.iQuantity as shl "+ //TODO 新算法
				", 1 as jiansh "+
				", 1 as lingsshl "+
				", W.iCost as dj" +
				", W.iMoney as je " +
				", W.cBatch as pihao " +
//				", W.dPDate as baozhiqi " +
//				", W.cExpirationdate as sxrq " +
				", W.dPDate as baozhiqi " +
				", null as quyubh "+
				", null as yspd "+
				", null as yuany "+
				", 1 as yew_type "+
				", 'N' as zt " + 
			"from PU_ArrivalVouch as T inner join PU_ArrivalVouchs  as W on T.ID= W.ID "+
			" where  ufts > %d and ufts <= %d "+
			"order by T.ID asc, irowno asc ";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 2);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "		if NOT EXISTS( select top 1 1 from jzt_rkjxdj where left(djbh,6)='A21CGD' and LEN(djbh)=14 )"+
		"select djbh = 'A21CGD00000001'"+
		"else "+
		" select djbh = 'A21CGD' + right('00000000' + cast( cast(right(max(djbh),8) as int) + 1 as nvarchar(8)),8) from jzt_rkjxdj where left(djbh,6)='A21CGD' and LEN(djbh)=14";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("djbh");
		int startIndex = Integer.parseInt(code.substring(6));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){
			
			this.parseData(2, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_rkjxdj", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_rkjxdj", updateMapData, 
						ImpStringUtil.commaStringToSetStr("u8djbm", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 2, newTime);
		}
		
		logger.info("finish, datasize:{},updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}

	/**
	 * jzt_mchk（单位客户资料表）, 客户档案 供应商档案 u8->九州通
	 */
	public void doEx_mchk(BaseDbcpDao src, BaseDbcpDao dst) {

		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(pubufts)) as newts from customer";

		String sql_getData = "use UFDATA_004_2016 select "
				+ "  'A21' + cCusCode as danwbh,"
				+ "cCusAbbName as dwmch,"
				+ "cCusName as danwqc,"
				+ "cCusName as danwjc,"
				+ "cCusName as zjm," 
				+	"cCusPerson as lxr,"
				+ "cCusPhone as lxrdh,"
				+ "case  when dEndDate IS NULL then 'Y' else 'N' end as beactive,"
				+ "dCusCreateDatetime as denglrq," 
				+ "isnull(dModifyDate,dCusCreateDatetime) as dmrq," 
				+ "cCusFax as faxno,	" 
				+ "cMemo as dwbz,	"
				+ "'N' as kemuhao,	" 
				+ "cCusAddress as dzdh," 
				+ "0 as printfa," 
				+ "'N' as sf_yez,"
				+ "'A21' as yez, " 
				+ "'N' as zt "
				+ "from Customer " + "where  pubufts > %d and pubufts <= %d";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 3);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "if NOT EXISTS( select top 1 1 from jzt_mchk where left(dwbh,3)='A21' and LEN(dwbh)=11 ) "
		+"select dwbh = 'A2100000001' "
		 + " else "
		 + "select dwbh = 'A21' + right('00000000' + cast( cast(right(max(dwbh),8) as int) + 1 as nvarchar(8)),8) from jzt_mchk where left(dwbh,3)='A21' and LEN(dwbh)=11";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("dwbh");
		int startIndex = Integer.parseInt(code.substring(3));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){

			this.parseData(3, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_mchk", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_mchk", updateMapData, 
						ImpStringUtil.commaStringToSetStr("danwbh", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 3, newTime);
		}
		
		logger.info("finish, datasize:{}, updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}
	
	

	/**
	 * jzt_spkfk（商量基础资料） 存货档案 u8->九州通
	 */
	public void doEx_spkfk(BaseDbcpDao src, BaseDbcpDao dst) {
		
		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(pubufts)) as newts from inventory";

		String sql_getData =" use UFDATA_004_2016 select "+
				"'' as spid,"+
				"'A21' + upper(cInvCode)  as spbh,"+
				"cInvName as spmch,	"+
				"cInvName as zjm,	"+
				"case  when dEDate IS NULL then 'Y' else 'N' end as beactive,"+
				"case when cAddress is null then 'undefine' else   cAddress end as shpchd, "+
				"cInvStd as shpgg,		"+
				"case when cEnterprise is null then 'undefine' else   cEnterprise end as shengccj, "+
				"case when cFile is null then 'undefine' else   cFile end as pizhwh, "+ //TODO u8中可能为null
				"cPreparationType as jixing,"+
				"dSDate as denglrq,			"+
				"dEDate as delrq,			"+
				"cCurrencyName as tongym,	"+
				"cLabel as zhucsb,			"+
				"fRetailPrice as lshj,		"+
				"dModifyDate as dmrq,		"+
				"iInvLSCost as zdshj,		"+
				"iHighPrice as zgshj,		"+
				"cQuality as zhilbz,			"+
				"'DWID0001483' as yez,			"+
				" '1' as caif_lid, "+
				" '1' as zbz, "+
				"1 as kaipdw_min, " +
				"'N' as sf_zp, "+
				"'N' as zt, "+
				"'K' as is_jg, "+
				" (select top 1 iChangRate from ComputationUnit where ComputationUnit.cGroupCode=inventory.cGroupCode order by iChangRate desc) as jlgg,"+
				"(select top 1 cComUnitName from ComputationUnit where ComputationUnit.cGroupCode=inventory.cGroupCode order by iChangRate desc) as dw,"+
				//"10 as jlgg, "+ //包装数量	整数	10	0	不为空。以最小拆分单位来看，一整箱有多少最少可拆分的单元
				"'1' as ypdl, "+ //药品大类	字符	12, 
				" '1' as cctj,"+
				" '2' as yewlx, "+
				"case when isnull(bImportMedicine,0)=0 then 'N' else 'Y' end as is_jkyp	"+
			"from inventory where pubufts >%d and pubufts <= %d";


		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 4);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "if NOT EXISTS( select top 1 1 from jzt_spkfk where left(spid,3)='A21' and LEN(spid)=11 ) "
		+"select spid = 'A2100000001' "
		 + " else "
		 + "select spid = 'A21' + right('00000000' + cast( cast(right(max(spid),8) as int) + 1 as nvarchar(8)),8) from jzt_spkfk where left(spid,3)='A21' and LEN(spid)=11";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("spid");
		int startIndex = Integer.parseInt(code.substring(3));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){
			
			this.parseData(4, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_spkfk", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_spkfk", updateMapData, 
						ImpStringUtil.commaStringToSetStr("spbh", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 4, newTime);
		}
		
		logger.info("finish, datasize:{},updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}
	
	/**
	 * jzt_mchk（单位客户资料表）, 客户档案 供应商档案 u8->九州通
	 */
	public void doEx_mchk_gys(BaseDbcpDao src, BaseDbcpDao dst) {

		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(pubufts)) as newts from vendor";

		String sql_getData = "use UFDATA_004_2016 select  'gen' as dwbh,"+
		"'A21' + cVenCode as danwbh,"+
		"cVenAbbName as dwmch,"+//	-- 单位名称
		"'gen' as dwbh_sj,"+//
		"cVenName as zjm, "+//-- 助记码 需要生成汉字首字母
		"cVenPerson as lxr,"+//	-- 客户联系人
		"cVenPhone as lxrdh, "+//-- 联系人电话
		//"cVenAddress as dzhdh, "+//(u8 255, 需要电话?)
		"cVenName as danwqc,	"+//	-- 单位全称 98
		"case  when dEndDate IS NULL then 'Y' else 'N' end as beactive,"+//-- 默认为Y，表示单位是活动状态；N表示单位被锁定
		"dVenCreateDatetime as denglrq,"+//	-- 客户创建日期 可以为空
		"cVenAbbName as danwjc,	"+//			-- 单位简称
		"isnull(dModifyDate,dVenCreateDatetime) as dmrq,	"+//		   --更新日期
			
		"cVenAddress as dzdh,"+//			-- 注册地址 
		"cVenFax as faxno,	"+//			-- 传真
		"cMemo as dwbz,		"+//			-- 单位备注
		"'N' as kemuhao,		"+//			-- 科目号

		"0 as printfa,		"+//			-- 打印方式
		"'A21' as yez,"+//
		"'N' as sf_yez,"+//
		"'N' as sf_yh"+//
			 " from Vendor " + "where  pubufts > %d and pubufts <= %d";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 5);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "if NOT EXISTS( select top 1 1 from jzt_mchk where left(dwbh,3)='A21' and LEN(dwbh)=11 ) "
		+"select dwbh = 'A2100000001' "
		 + " else "
		 + "select dwbh = 'A21' + right('00000000' + cast( cast(right(max(dwbh),8) as int) + 1 as nvarchar(8)),8) from jzt_mchk where left(dwbh,3)='A21' and LEN(dwbh)=11";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("dwbh");
		int startIndex = Integer.parseInt(code.substring(3));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){

			this.parseData(3, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_mchk", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_mchk", updateMapData, 
						ImpStringUtil.commaStringToSetStr("danwbh", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 5, newTime);
		}
		
		logger.info("finish, datasize:{}, updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}
	
	/**
	 * jzt_ckjxdj（出库进销单据表，包含出库、购退单据，具体以表中ddlx字段来区分）采购退货单
	 */
	public void doEx_ckjxdj_cgth(BaseDbcpDao src, BaseDbcpDao dst) {
		
		//TODO top 5000 be deleted
		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(ufts)) as newts from DispatchList  ";
		String sql_getData =" use UFDATA_004_2016 select top 5000 "+
				"'1' as djbh	"+//	-- 单据编号,insert语句时生成
				",'A21GTD' + cdlcode as u8djbm	"+//	-- U8发货单编码
				",'A21' + T.cCusCode as dwbh	"+//		-- 单位内码，这样查出来的是单位编号，应用通过以下SQL查出单位内码
													//-- select top 1 dwbh from jzt_mchk where danwbh = '此值'
				",T.dDate as rq	"+//					-- 日期
				",T.dcreatesystime as ontime "+//			-- 开票时间 取当时开票时间。
				", case when T.ccusperson is null then 'undefine' else   T.ccusperson end as ywy	"+//			-- 业务员 TODO null problem
				",T.cmaker as username	"+//			-- 操作员
				",'N' as sf_tbj		"+//				-- 是否退补价
				",null as djbh_y		"+//				-- 上级单据编号
				",'3' as thfs		"+//				-- 提货方式
				",'0' as scf			"+//				-- 上传方
				",null as Dwid_ej	"+//				-- 二级单位内码
				",null as djbh_bd	"+//				-- 补单单号
				",'N' as Sf_ffzp	"+//					-- 是否发放赠品
				",'1' as zpfffs		"+//				-- 赠品发放方式
				",null as tyfk			"+//			-- 托运付款
				",T.cmemo as khbz	"+//				-- 客户备注
				",'1' as ddlx		"+//				-- 订单类型	没有发货单，暂是为1	"1 销售出库 2 调拨出库 3 连锁 4 购进退出 5 库存整理 6 直通订单
				",'6' as danjlx		"+//				-- 单据类型 U8中没有看到，暂时为6
				",null as xslx		"+//				-- 税票类型
				",null as pslx		"+//				-- 配送类型
				",'0' as fkfs		"+//				-- 付款方式
				",'undefine' as cgy "+ //
				",'DWID0001483' as yez		"+//				-- 业主内码
				",1 as yspd		"+//				-- 验收评定
				",1 as yuany		"+//				-- 退货原因
				",3 as yew_type		"+//				-- 业务类型
				",T.dmoddate  as dmrq		"+//			-- 操作日期
				",'N' as ZT			"+//				--
				",'N' as sf_gxht		"+//				-- 是否打印购销合同
				",(select top 1 cPersonPhone from Person where cPersonCode = cpersoncode) as xsywydh "+//-- 业务员电话
		//	-- 以下是子表字段
				",W.irowno as Dj_sort	"+//			-- 行号
				",'A21' + W.cinvcode as spid	"+//		-- 此值查出来的是存货集团商品编码，插入时应根据此值查出内码
													//-- select top 1 spid from jzt_spkfk where spbh='此值'
				",W.iquantity as shl	"+//				-- 数量

				", case when W.itaxunitprice is null then '98' else   W.itaxunitprice end as dj "+//TODO
				", case when W.isum is null then '98' else   W.isum end as hsje "+//TODO
				",W.isettleprice as hesdj		"+//		-- 结算单价
				",W.cbatch as ph	"+//					-- 批号
				",null as Sf_cxsp	"+//				-- 是否促销商品
				",null as cxms	"+//					-- 促销描述
				",W.fsalecost as lshj	"+//			-- 零售单价
				",W.isettlenum as jsje		"+//		-- 结算金额
				",W.iQuotedPrice  as dckhcbj	 "+//		-- 调出考核成本价	
			"from DispatchList  as T inner join DispatchLists as W on T.dlid = W.dlid  "+//
			"where ufts >%d and ufts <= %d "+//
			"order by T.dlid asc, irowno asc ";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 6);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "		if NOT EXISTS( select top 1 1 from jzt_ckjxdj where left(djbh,6)='A21GTD' and LEN(djbh)=14 )"+
		"select djbh = 'A21GTD00000001'"+
		"else "+
		" select djbh = 'A21GTD' + right('00000000' + cast( cast(right(max(djbh),8) as int) + 1 as nvarchar(8)),8) from jzt_ckjxdj where left(djbh,6)='A21GTD' and LEN(djbh)=14";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("djbh");
		int startIndex = Integer.parseInt(code.substring(6));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){
			
			this.parseData(6, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_ckjxdj", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_ckjxdj", updateMapData, 
						ImpStringUtil.commaStringToSetStr("u8djbm", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 6, newTime);
		}
		
		logger.info("finish, datasize:{},updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
	}
	
	private void doEx_rkjxdj_xsth(BaseDbcpDao src, BaseDbcpDao dst) {
		String sql_newLastTime = "use UFDATA_004_2016 select convert(bigint,max(convert(bigint,convert(timestamp ,convert(money,ufts))))) as newts from Sales_FHD_T where bReturnFlag = 1 ";
		String sql_getData =" use UFDATA_004_2016 select "+
				"1 as djbh "+ //后面会覆盖掉  A21CGD00000001
				",'A21XTD' + cdlcode as u8djbm "+
				",'A21' + T.ccuscode as dwbh "+
				",T.ddate as rq "+
				",T.dcreatesystime as ontime "+				
				",4 as rktype "+
				", 0 as scf "+
				", case when T.ccontactname is null then 'undefine' else   T.ccontactname end as lxr "+
				", case when T.ccontactname is null then 'undefine' else   T.ccontactname end as shouhy "+
				", case when T.cpersonname is null then 'undefine' else   T.cpersonname end as ywy "+
				", null as lxrdh "+
				", null as thlb "+
				", 'DWID0001483' as yez "+
				",  W.irowno as dj_sort " +
				",'A21' + W.cInvCode as spid " + //后面会覆盖掉  A21CGD00000001
				", W.iQuantity as shl "+ //TODO 新算法
				", 1 as jiansh "+
				", 1 as lingsshl "+
				", W.itaxunitprice as dj" +
				", W.iMoney as je " +
				",'undefine' as username"+
				", case when W.cBatch is null then 'undefine' else  W.cBatch end as pihao "+
				", 2 as yspd "+
				", case when W.cmemo is null then 'undefine' else  W.cmemo end as yuany "+
				", 1 as yew_type "+
				", 'N' as zt " + 
				"from Sales_FHD_T as T inner join Sales_FHD_W as W on T.dlid = W.dlid "+
				"where convert(bigint,convert(timestamp ,convert(money,ufts))) > %d and convert(bigint,convert(timestamp ,convert(money,ufts))) <=%d "+
				"order by T.dlid asc, irowno asc ";

		//lastUpate time and new lastupdate time
		List<Map<String, Object>> timeRet = src.doSql(0, sql_newLastTime, true);
		if (timeRet == null || timeRet.size() == 0) {
			throw new RuntimeException("do sql failed:" + sql_newLastTime);
		}
		Long lastTime = this.getLastTS(dst, 7);
		Long newTime = (Long) timeRet.get(0).get("newts");
		
		//获得单位内码
		String sql_code = "		if NOT EXISTS( select top 1 1 from jzt_rkjxdj where left(djbh,6)='A21XTD' and LEN(djbh)=14 )"+
		"select djbh = 'A21XTD00000001'"+
		"else "+
		" select djbh = 'A21XTD' + right('00000000' + cast( cast(right(max(djbh),8) as int) + 1 as nvarchar(8)),8) from jzt_rkjxdj where left(djbh,6)='A21XTD' and LEN(djbh)=14";		
		List<Map<String, Object>> mapData = src.doSql(0, sql_code, true);
		if ( ImpCollUtil.isNullColl(mapData) ){
			throw new RuntimeException("List<Map<String, Object>> mapData = src.doSql(0, sql_code, true); null");
		}
		String code = (String) mapData.get(0).get("djbh");
		int startIndex = Integer.parseInt(code.substring(6));
		
		//get src sql data
		sql_getData = String.format(sql_getData, lastTime, newTime);
		mapData = src.doSql(0, sql_getData, true);
		
		//has data do input
		List<Map<String, Object>> updateMapData = new ArrayList<Map<String,Object>>();
		if ( !ImpCollUtil.isNullColl(mapData) ){
			
			this.parseData(7, dst, mapData, updateMapData, startIndex);
			//do input data to dst
			Connection conn = dst.doTransaction(0);
			int ret = dst.addObjectsMapByConn("jzt_rkjxdj", mapData, conn, "use data ");
			if ( ret == 1 ){
				ret = dst.updateObjectsMapByConn("jzt_rkjxdj", updateMapData, 
						ImpStringUtil.commaStringToSetStr("u8djbm", ","), conn, "use data ", true);
			}
			dst.doTransactionEnd(conn, ret ==1);
			if ( ret == 1)
				this.setLastTS(dst, 7, newTime);
		}
		
		logger.info("finish, datasize:{},updateNum:{}, sql:{}", ImpCollUtil.getCollSizeStr(mapData), updateMapData.size(), sql_getData);
		
	}

	public long getLastTS(BaseDbcpDao dst, int index) {
		String tableName = "";
		switch (index) {
		case 1:
			tableName = "ckjxdj";
			break;
		case 2:
			tableName = "rkjxdj";
			break;
		case 3:
			tableName = "mchk";
			break;
		case 4:
			tableName = "spkfk";
			break;
		case 5:
			tableName = "mchk_gys";
			break;
		case 6:
			tableName = "ckjxdj_cgth";			
			break;			
		case 7:
			tableName = "rkjxdj_xsth";			
			break;
		}
		if (tableName.isEmpty()) {
			throw new RuntimeException("talbeName must not empty, must ckjxdj , .... ");
		}

		String sql = String.format("use data select ts from jzt_u8_timestamp where tablename='%s'", tableName);

		List<Map<String, Object>> ret = dst.doSql(0, sql, true);
		if (ret == null || ret.size() == 0) {
			throw new RuntimeException("jzt_u8_timestamp find tablename failed " + tableName);
		}

		Long lastTime = (Long) ret.get(0).get("ts");
		return lastTime;
	}

	public long setLastTS(BaseDbcpDao dst, int index, Long updateTime) {
		String tableName = "";
		switch (index) {
		case 1:
			tableName = "ckjxdj";
			break;
		case 2:
			tableName = "rkjxdj";
			break;
		case 3:
			tableName = "mchk";
			break;
		case 4:
			tableName = "spkfk";
			break;
		case 5:
			tableName = "mchk_gys";
			break;
		case 6:
			tableName = "ckjxdj_cgth";			
			break;
		case 7:
			tableName = "rkjxdj_xsth";			
			break;			
		}
		if (tableName.isEmpty()) {
			throw new RuntimeException("talbeName must not empty, must ckjxdj , .... ");
		}

		String sql = String.format("use data  update jzt_u8_timestamp set ts=%d where tablename='%s'", updateTime, tableName);

		dst.doSql(0, sql, false);
		return 0l;
	}

	public void parseData(int index, BaseDbcpDao dst, List<Map<String, Object>> data, List<Map<String, Object>> dstData, int startCode) {

		switch ( index ){
		case 1:
			for ( int i=data.size()-1; i>=0; i--){

				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select djbh,spid,dwbh from jzt_ckjxdj where u8djbm = '%s'", dd.get("u8djbm"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("djbh", String.format("A21XSD%s", dd.get("u8djbm").toString().substring(8)));
					String sql =  "use data select dwbh from jzt_mchk where danwbh='"+dd.get("dwbh")+"'";
					Map<String, Object> dwbnD = dst.doSqlOfSimple(0,sql, true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					sql =  "select spid from jzt_spkfk where spbh='"+dd.get("spid")+"'";
					dwbnD = dst.doSqlOfSimple(0, sql , true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					startCode ++;
				}

			}			
			break;						
		case 2:
			for ( int i=data.size()-1; i>=0; i--){
//				"1 as djbh		"+ //后面会覆盖掉  A21XSD00000001
//				",1 as dwbh" + //后面会覆盖掉
//				",1 as spid" + //后面会覆盖掉
				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select djbh,spid,dwbh from jzt_rkjxdj where u8djbm = '%s'", dd.get("u8djbm"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("djbh", String.format("A21CGD%s", dd.get("u8djbm").toString().substring(8)));
					String sql =  "use data select dwbh from jzt_mchk where danwbh='"+dd.get("dwbh")+"'"; //TODO
					Map<String, Object> dwbnD = dst.doSqlOfSimple(0,sql, true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					sql =  "select spid from jzt_spkfk where spbh='"+dd.get("spid")+"'";
					dwbnD = dst.doSqlOfSimple(0, sql , true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					
					startCode ++;
				}

			}						
			break;
		case 3:
			for ( int i=data.size()-1; i>=0; i--){
				
				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select dwbh_sj, dwbh, zjm from jzt_mchk where danwbh = '%s'", dd.get("danwbh"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
										
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("dwbh_sj", String.format("A21%08d", startCode));
					dd.put("dwbh", String.format("A21%08d", startCode));
					String jzm = (String) dd.get("zjm");
					if ( !ImpStringUtil.isEmpty(jzm) ){
						jzm = PinyinUtils.getPinyin(jzm, true);
						dd.put("zjm", jzm);
					}
					startCode ++;
				}

			}			
			break;
		case 4:
			for ( int i=data.size()-1; i>=0; i--){
				
				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select spid, zjm from jzt_spkfk where spbh = '%s'", dd.get("spbh"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
										
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("spid", String.format("A21%08d", startCode));
					String jzm = (String) dd.get("zjm");
					if ( !ImpStringUtil.isEmpty(jzm) ){
						jzm = PinyinUtils.getPinyin(jzm, true);
						dd.put("zjm", jzm);
					}
					startCode ++;
				}

			}			
			break;		
		case 6:
			for ( int i=data.size()-1; i>=0; i--){
//				"1 as djbh		"+ //后面会覆盖掉  A21XSD00000001
//				",1 as dwbh" + //后面会覆盖掉
//				",1 as spid" + //后面会覆盖掉
				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select djbh,spid,dwbh from jzt_ckjxdj where u8djbm = '%s'", dd.get("u8djbm"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("djbh", String.format("A21GTD%s", dd.get("u8djbm").toString().substring(8)));
					String sql =  "select dwbh from jzt_mchk where danwbh='"+dd.get("dwbh")+"'";
					Map<String, Object> dwbnD = dst.doSqlOfSimple(0,sql, true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						return ;//TODO
						//throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					sql =  "select spid from jzt_spkfk where spbh='"+dd.get("spid")+"'";
					dwbnD = dst.doSqlOfSimple(0, sql , true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					startCode ++;
				}

			}			
			break;		
		case 7:
			for ( int i=data.size()-1; i>=0; i--){
//				"1 as djbh		"+ //后面会覆盖掉  A21XSD00000001
//				",1 as dwbh" + //后面会覆盖掉
//				",1 as spid" + //后面会覆盖掉
				Map<String, Object> dd = data.get(i);				
				String sql_get =String.format("use data select djbh,spid,dwbh from jzt_rkjxdj where u8djbm = '%s'", dd.get("u8djbm"));
				Map<String, Object> objD = dst.doSqlOfSimple(0, sql_get, true);
				if ( ! ImpCollUtil.isNullMap(objD) ){
					//add to update listmap
					dstData.add(dd);
					dd.putAll(objD);
					data.remove(i);
				}
				else {
					//insert new one
					dd.put("djbh", String.format("A21XTD%s", dd.get("u8djbm").toString().substring(8)));
					String sql =  "use data select dwbh from jzt_mchk where danwbh='"+dd.get("dwbh")+"'";
					Map<String, Object> dwbnD = dst.doSqlOfSimple(0,sql, true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					sql =  "select spid from jzt_spkfk where spbh='"+dd.get("spid")+"'"; //TODO
					dwbnD = dst.doSqlOfSimple(0, sql , true);
					if ( ImpCollUtil.isNullMap(dwbnD) ){
						throw new RuntimeException("sql ret no data, sql: "+ sql);
					}
					dd.putAll(dwbnD);
					startCode ++;
				}

			}						
			break;			
		}

	}
	
	/**
	 * 销售出库单
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_ckd(BaseDbcpDao src, BaseDbcpDao dst) {
		
	String sqlMain =	"use data select	djbh as FHD_CODE,dwbh, rq, ywy, Dj_sort, spid, shl, dj, ph,baozhiqi,sxrq from inf_erp_imp_ck_bill "+
			"where djbh not in (select jzt_bill_code from inf_gen_rel where bill_type=1) and yew_type='销售出库' order by djbh asc, Dj_sort asc";
	Map<String, Object> maindataMap = dst.doSqlOfSimple(0, sqlMain, true);
		
	String sqlMcString = "use data select danwbh as dwbh from jzt_mchk where dwbh= '%s'";
	sqlMcString = String.format(sqlMcString, maindataMap.get("dwbh"));
	
	Map<String, Object> tmpData = dst.doSqlOfSimple(0, sqlMcString, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		return;
	}
	
	//1.2、先转换成U8中的客户编码，再判断是否存在，不存在报错
	String dwbhU8 = tmpData.get("dwbh").toString().substring(3);

	String sqlTmp = "use UFDATA_004_2016 select 1 from Customer where cCusCode = '" + dwbhU8+"'";
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		return;
	}
	
	sqlTmp = String.format("use UFDATA_004_2016 select 1 from Sales_FHD_T where cdlcode = '%s' ", "00"+maindataMap.get("FHD_CODE").toString().substring(6));
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		return;
	}
	
//	sqlTmp = String.format("use UFDATA_004_2016 select 1 from Person where cPersonName='%s' ", maindataMap.get("ywy"));
//	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
//	if ( tmpData==null || tmpData.size() == 0 ){
//		return;
//	}
		
	sqlTmp = String.format("use UFDATA_004_2016 select 1 from Sales_FHD_W where dlid = (select top 1 dlid from Sales_FHD_T where cdlcode='%s') and irowno = '%s' ",  "00"+maindataMap.get("FHD_CODE").toString().substring(6), maindataMap.get("Dj_sort"));
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		return;
	}

	if ( maindataMap.get("spid")== null || maindataMap.get("spid").toString().length() <= 0  ){
		logger.info("原始单据上没有填写，它就为NULL了");
		return;
	}
	sqlTmp = String.format("use data select 1 from jzt_spkfk where spid='%s'", maindataMap.get("spid"));
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		logger.info("失败报错，存货内码不存在");
		return;
	}
	
	sqlTmp = String.format("use data select spbh as spid from jzt_spkfk where spid= '%s' ", maindataMap.get("spid"));
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		return;
	}
	String spidU8 = tmpData.get("spid").toString().substring(3);
	
	sqlTmp = String.format("use UFDATA_004_2016 select 1 from Inventory where cInvCode = '%s' ", spidU8);
	tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	if ( tmpData==null || tmpData.size() == 0 ){
		logger.info("先转换成U8中的存货编码，再判断是否存在，不存在报错");
		return;
	}
			
	//-- 生成新的单据编码
	String sqlDanju = "use UFDATA_004_2016  DECLARE @cCode VARCHAR(10) " + " if NOT EXISTS( select top 1 1 from rdrecord32 where LEN(cCode)=10 ) "
	+ " select  '0000000001' as dd " + "else  select	right('0000000000' + cast( cast(right(max(cCode),10) as int) + 1 as nvarchar(10)),10) as dd   from rdrecord32 where LEN(cCode)=10 ";
	Map<String, Object> cCodeMap = dst.doSqlOfSimple(0, sqlDanju, true);
	
	Map<String, Object> insertDataMap = null;
	String sqlInsert = "use UFDATA_004_2016  select %s as cCode, " + 
			"0 as bRdFlag,"+
			"'32' as cVouchType,"+
			"'普通销售' as cBusType,"+
			"'发货单' as cSource,"+
			"'%s' as cBusCode,"+ //FHD_CODE
			" '01' as cWhCode,"+
			" '%s' as dDate,"+ //rq
			"  (select top 1 crdcode from Sales_FHD_T where cdlcode='%s' ) as cRdCode,"+ //FHD_CODE
			" (select top 1 cDepCode from Person where cPersonName='%s' ) as cDepCode,"+ //ywy
			"  (select top 1 cPersonCode from Person where cPersonName='%s' ) as cPersonCode,"+ //ywy
			" (select top 1 cstcode from Sales_FHD_T where cdlcode='%s') as cSTCode,"+ //FHD_CODE
			" '%s' as cCusCode,"+ //dwbh
			" (select top 1 dlid  from Sales_FHD_T  where cdlcode='%s' ) as cDLCode,"+ //FHD_CODE
			" 0 as bTransFlag,"+
			" 0 as bpufirst,"+
			" 0 as biafirst,"+ 
			" 87 as VT_ID,"+ //单据模版号 需要写死，需要和jzt沟通
			" 0 as bIsSTQc,"+ //
			" 0 as bOMFirst,"+ //
			" 0 as bFromPreYear,"+ //
			" 0 as bIsComplement,"+ //
			" 0 as iDiscountTaxType,"+ //
			" 0 as ireturncount,"+ //
			" 0 as iverifystate,"+ //
			" 0 as iswfcontrolled,"+ //
			" '%s' as dnmaketime,"+ //制单时间  system.currenttime()
			" 0 as bredvouch,"+ //
			" 0 as iPrintCount,"+ //
			" 'lst32|+%s' as csysbarcode,"+ //
			" '%s' as cinvoicecompany, "+ //dwbh		
			" (select max(ID) +1 FROM rdrecord32) as ID "; //		

	sqlInsert = String.format(sqlInsert, cCodeMap.get("dd"),"00"+maindataMap.get("FHD_CODE").toString().substring(6),maindataMap.get("rq"),"00"+maindataMap.get("FHD_CODE").toString().substring(6),maindataMap.get("ywy")
			,maindataMap.get("ywy"),"00"+maindataMap.get("FHD_CODE").toString().substring(6) , dwbhU8 ,"00"+maindataMap.get("FHD_CODE").toString().substring(6), DateUtil.getCurrentDate(DateUtil.DEFAULT_PATTERN),
			cCodeMap.get("dd"), dwbhU8, cCodeMap.get("dd") );
	insertDataMap = dst.doSqlOfSimple(0, sqlInsert, true);
	
	//子表数据	
	Map<String, Object> subTableData = null;
	String subSql =  "use UFDATA_004_2016  select top 1 AutoID, "+
			" csocode,"+
			"  isosid,"+
			" iinvexchrate,"+
			" idemandseq,"+
			" idemandtype,"+
			" cdemandid,"+
			" cordercode,"+
			" iorderrowno,"+
			" cunitid "+
			" from  Sales_FHD_W where dlid = (select top 1 dlid from Sales_FHD_T where cdlcode='%s' ) and irowno = %s";
	subSql = String.format(subSql, "00"+maindataMap.get("FHD_CODE").toString().substring(6), maindataMap.get("Dj_sort"));

	//-- 生成新的单据编码
	sqlTmp = "use UFDATA_004_2016  SELECT top 1 CAST(cValue AS int) as iStrsQuanDecDgt from accinformation where cName='iStrsQuanDecDgt'";
	Map<String, Object> sub_tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	subTableData = dst.doSqlOfSimple(0, subSql, true);
	
	sqlTmp = "use UFDATA_004_2016  SELECT ROUND(%f/%f,%d) as iNum";
	sqlTmp = String.format(sqlTmp, maindataMap.get("shl"), subTableData.get("iinvexchrate"), sub_tmpData.get("iStrsQuanDecDgt"));
	sub_tmpData = dst.doSqlOfSimple(0, sqlTmp, true);
	
	String sqlSubDataSql = "use UFDATA_004_2016  select %s as iRSRowNO," +  //@Dj_sort
			" '%s' as cInvCode," +  //spid
			" %s as iQuantity," +  //@shl
			" %s as iNum," +  //@@iNum
			" %s as iUnitCost," +  //@dj
			" case when %s is null then NULL else ROUND( %s * %s ,2)end as iPrice,"+ //dj, shl*dj
			" %s as cBatch," +  //@ph
			" 0 as iFlag," +  //
			" 0 as dVDate," +  //sxrq
			" '%s' as iDLsID," +  //AutoID
			" %s as iNQuantity," +  //@shl
			" %s as iNNum," +  //@iNum
			" %s as cAssUnit," +  //@cunitid
			" '%s' as dMadeDate," +  //@baozhiqi
			" datediff(day, %s, %s) as iMassDate," +  //@baozhiqi, sxrq
			" 3 as cMassUnit," +
			" 0 as bLPUseFree," +
			" 0 as iOriTrackID," +
			" 1 as bCosting," +
			" 0 as bVMIUsed," +
			" %s as iinvexchrate," + //@iinvexchrate
			" '%s' as cbdlcode," + //@FHD_CODE
			" 2 as iExpiratDateCalcu," +
			" CONVERT(varchar(10),DATEADD(day,-1,%s), 120 ) as cExpirationdate," + //sxrq
			" DATEADD(day,-1,'%s') as dExpirationdate,"+ // //sxrq
			" %s as iorderdid," + //@isosid
			" case when '%s' IS NULL then 0 else 1 end as iordertype," + //isosid
			" '%s' as iordercode," + //cordercode
			" %s as iorderseq," + //@iorderrowno
			" %s as ipesotype," + //@idemandtype
			" '%s' as cpesocode," + //@cdemandid
			" %s as ipesoseq," + //@idemandseq
			" '%s' as isodid," + //@isosid
			" 0 as isotype," + //
			" '%s' as csocode," + //@csocode
			" %s as irowno," + //@Dj_sort
			" 'lst32|'+'%s|'+ CAST( '%s' as varchar(8)) as cbsysbarcode," + //cCode, @Dj_sort
			" 0 as bIAcreatebill," + //
			" 0 as bsaleoutcreatebill," + //
			" 1 as bneedbill, "+ //
			" (select max(ID)+1 from rdrecords32) as ID , "+
			" (select max(autoid)+1 from rdrecords32) as AutoID "; //
	sqlSubDataSql = String.format(sqlSubDataSql, maindataMap.get("Dj_sort"), maindataMap.get("spid"), maindataMap.get("shl"), sub_tmpData.get("iNum")
			, sub_tmpData.get("cAssUnit"), sub_tmpData.get("cAssUnit"),  maindataMap.get("shl"),sub_tmpData.get("cAssUnit"), maindataMap.get("ph"),subTableData.get("AutoID"),maindataMap.get("shl"),
			sub_tmpData.get("iNum"),subTableData.get("cunitid"), maindataMap.get("baozhiqi"), maindataMap.get("baozhiqi"), maindataMap.get("sxrq")
			, sub_tmpData.get("iinvexchrate"), "00"+maindataMap.get("FHD_CODE").toString().substring(6), maindataMap.get("sxrq"), maindataMap.get("sxrq")
			, sub_tmpData.get("isosid"), sub_tmpData.get("isosid"), sub_tmpData.get("cordercode"), sub_tmpData.get("iorderrowno")
			, sub_tmpData.get("idemandtype"), sub_tmpData.get("cdemandid"), sub_tmpData.get("idemandseq"), sub_tmpData.get("isosid")
			, sub_tmpData.get("csocode"), maindataMap.get("Dj_sort"), insertDataMap.get("cCode"), maindataMap.get("Dj_sort"));
	Map<String, Object> insertDataMap_sub = dst.doSqlOfSimple(0, sqlSubDataSql, true);
	
	//插入数据
	List<Map<String, Object>> listDataMap = new ArrayList<Map<String,Object>>();
	Connection conn = src.doTransaction(0);
	listDataMap.add(insertDataMap);
	
	int ret = src.addObjectsMapByConn("rdrecord32", listDataMap, conn, "use UFDATA_004_2016 ");
	if ( ret != 1 ){
		src.doTransactionEnd(conn, ret ==1);
	}
	listDataMap.clear();
	
	listDataMap.add(insertDataMap_sub);
	ret = src.addObjectsMapByConn("rdrecords32", listDataMap, conn, "use UFDATA_004_2016 ");
	
	src.doTransactionEnd(conn, ret ==1);
	
	}

	/**
	 * 销售出库复核记录
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_xsch_fhjl(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}
	
	/**
	 * 运输记录
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_ysjl(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}
	
	/**
	 * 销售退货入库质量验收
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_xsth_rkzlys(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}
	
	/**
	 * 药品入库质量验收
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_yp_rkzlys(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}
	
	/**
	 * 采购退货出库质量复核
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_cgth_zlfh(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}
	
	/**
	 * 养护记录
	 * @param src
	 * @param dst
	 */
	public void doEx_Imp_cgth_yhjl(BaseDbcpDao src, BaseDbcpDao dst) {
		
		
	}

}
